<?php
/**
 * Created by PhpStorm.
 * User: rain
 * Date: 2018/4/5
 * Time: 下午4:51
 */

namespace App\Http\Controllers\Api;


use App\Models\GoodsComment;
use App\Models\Orders;
use App\Models\Users;
use App\Models\FormIds;
use App\Services\UserService;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class UserController extends AuthorizedController
{
    private $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }


    public function mobile(Request $request)
    {
        $rules = [
            'code' => 'required|string',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()){
            return $this->error();
        }

        try{
            $authType = $request->get('auth_type', 0);
            $authTargetId = $request->get('auth_target_id', 0);
            $user = $this->userService->mobile($request->apiUser, $request->code, $authType, $authTargetId);

            return $this->success(['user' => $user]);
        }catch(\Exception $e){
            return $this->error($e->getMessage());
        }

    }

    public function index(Request $request)
    {
        $user = $request->apiUser;

        $buyGoods = Orders::where([
            'user_id' => $user->id,
            'status' => Orders::STATUS_SUCCESS
        ])->select(['goods_type', 'goods_id'])->get();

        unset($user->id);

        return $this->success(['user' => $user, 'buy_goods' => $buyGoods]);
    }


    public function wxAuth(Request $request)
    {
        $rules = [
            'encrypted_data' => 'required|string',
            'iv' => 'required|string',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()){
            return $this->error();
        }

        try{
            $user = $this->userService->wxAuth($request->apiUser, $request->encrypted_data, $request->iv);

            return $this->success(['user' => $user]);
        }catch(\Exception $e){
            return $this->error($e->getMessage());
        }

    }


    public function unAuth()
    {
        return $this->error('登录认证失败', 403);
    }

    public function wxProfile(Request $request)
    {
        /** @var \App\User $user */
        $user = $request->apiUser;

        $user->nick_name = $request->get('nickName', '');
        $user->avatar = $request->get('avatarUrl', '');

        //        $user->gender = $request->get('gender', '');
        //        $user->country = $request->get('country', '');
        //        $user->province = $request->get('province', '');
        //        $user->city = $request->get('city', '');
        //        $user->language = $request->get('language', '');

        if (empty($user->avatar)){
            $user->avatar = User::DEFAULT_AVATAR;
        }

        $user->save();

        return $this->success(['user' => $user]);
    }

}
